package models.security.utils;

import java.util.List;
import java.util.UUID;

import framework.security.store.SecurityStoreFactory;
import framework.utils.MD5Util;
import framework.utils.SecurityUtil;
import models.security.Permission;
import models.security.Resource;
import models.security.Role;
import models.security.User;
import play.jobs.Job;
import play.jobs.OnApplicationStart;

@OnApplicationStart
public class SystemInit extends Job {

    @Override
    public void doJob() throws Exception {
        ResourceUtil.initResource();
        SecurityStoreFactory.getInstance().getStore(SecurityUtil.RESOURCE_STORE).storeResource(Resource.querySecurityMenus());
        if(User.count()==0){
            initAdmin();
        }
    }

    
    public static void initAdmin(){
        User admin = new User("系统管理员","admin");
        String secretKey = UUID.randomUUID().toString();
        admin.securityKey = secretKey;
        admin.password= MD5Util.encodeToStr("admin"+secretKey);
        admin.save();
        List<Permission> permissions = Permission.findAll();
        Role role = new Role();
        role.name="超级管理员";
        role.permissions.addAll(permissions);
        role.ifSystem=1;
        role.save();
        admin.roles.add(role);
        admin.save();
    }
}
